package cn.JHai.controller;

import cn.JHai.dao.MusicDao;
import cn.JHai.domain.Music;
import cn.JHai.service.impl.MusicServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@Controller
@RequestMapping("/audio")
public class AudioController {

    @Autowired
    MusicServiceImp musicServiceImp;

    //清空
    @RequestMapping("clear")
    public void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        ArrayList<Music> music = new ArrayList<Music>();
        session.setAttribute("musicPlayList", music);
        System.out.println("清理成功");
    }

    //删除
    @RequestMapping("del")
    public void del(String mid,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("删除开始");
        HttpSession session = request.getSession();
        //@SuppressWarnings("unchecked")
        ArrayList<Music> list = (ArrayList<Music>) session.getAttribute("musicPlayList");
        if(list!=null)
        {
            for(int i =0 ; i<list.size() ; i++){
                Music music = (Music) list.get(i);
                if( (music.getMid()+"").equals(mid)){
                    list.remove(i);
                    System.out.println("删除成功"+i);
                    i--;
                }
            }

        }
    }

    //
    @RequestMapping("getSrc")
    public void getSrc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String mid = request.getParameter("mid");
        Music music = musicServiceImp.find(mid);
        if(music!=null) {
            out.write("{\"src\":\""+music.getSrc()+"\"}");
            System.out.println("{\"src\":\""+music.getSrc()+"\"}");
            System.out.println("成功");
        }


    }

}
